package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pojo.Provider;
import pojo.User;
import service.ProviderService;
import tools.Constants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
@RequestMapping("/provider")
public class ProviderController {

    @Autowired
    private ProviderService providerService;

    @RequestMapping(value = "/query",method = RequestMethod.GET)
    public String getProvider(String queryProCode, String queryProName, Model model, HttpServletRequest request){
        request.setAttribute("providerList",providerService.getProvier(queryProCode,queryProName));
        return "providerlist";
    }
    @RequestMapping(value = "/query",method = RequestMethod.POST)
    public String getProviderFindId(String queryProCode, String queryProName, Model model, HttpServletRequest request){
        request.setAttribute("providerList",providerService.getProvier(queryProCode,queryProName));
        return "providerlist";
    }

    @RequestMapping("provideradd.html")
    public String getProviderAdd(){

        return "provideradd";
    }

    @RequestMapping("providersave.html")
    public String getProviderSave(Provider provider, Model model, HttpSession session){
        User loginUser= (User) session.getAttribute(Constants.USER_SESSION);
        provider.setCreatedBy(loginUser.getId());
        provider.setCreationDate(new Date());
        if (providerService.add(provider)){
            return "redirect:/provider/query";
        }
       return "providerlist";
    }

    @RequestMapping("/providerquery/{id}")
    public String getProviderquery(@PathVariable("id")String id, Model model){
        model.addAttribute("provider",providerService.getProviderById(id));
        return "providerview";
    }

    @RequestMapping("/providermodify/{id}")
    public String getProvidermodify(@PathVariable("id")String id, Model model){
        model.addAttribute("provider",providerService.getProviderById(id));
        return "providermodify";
    }

    @RequestMapping("/providermodifysave")
    public String getProvidermodifysave(Provider provider, Model model){
        if (providerService.modify(provider)){
            return "redirect:/provider/query";
        }
        return "providermodify";
    }

}
